package treazy.ultimate.stats;

import java.util.ArrayList;
import android.app.ActionBar;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ViewTeamsActivity extends ListActivity {
	/** Called when the activity is first created. */
	private ArrayList<Team> teamList;
	private ArrayList<String> teamNames;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		ActionBar actionBar = getActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(true);
		
		DatabaseHandler db = new DatabaseHandler(this);
		teamList = db.getAllTeams();
		
		teamNames = new ArrayList<String>();
		
		if(teamList.isEmpty()) { 
			teamNames.add("No Teams");
		} else {
			for(Team t: teamList){
				teamNames.add(t.getName());
			}	
		}
		setListAdapter(new ArrayAdapter<String>(this, R.layout.viewteams, R.id.teamsListPage, teamNames));
		ListView listView = getListView();
		listView.setTextFilterEnabled(true);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				if(teamNames.get(0) != "No Teams") {
					Object selectedTeam = parent.getItemAtPosition(position);
					Intent i = new Intent(getApplicationContext(), TeamActivity.class);
					i.putExtra("TeamName", selectedTeam.toString());
					startActivity(i);
				}
			}
		});
		
	}
	
	@Override 
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.teamsmenu, menu);
	    
	    return true;
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.newteam:
	        	startActivity(new Intent(getApplicationContext(), NewTeamActivity.class));
	            return true;
	        case android.R.id.home:
	        	Intent i = new Intent(getApplicationContext(), UltiSystemsActivity.class);
	        	i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
	        	startActivity(i);
	        	return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}
}